<?php

namespace App\Exports;

use App\Models\CommodityActivity;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\MorphToMany;
use Illuminate\Support\Carbon;
use Maatwebsite\Excel\Concerns\FromQuery;

class CommodityActivityExport extends BaseExport implements FromQuery
{
    public function headings(): array
    {
        return [
            '活动编号',
            '商品名称',
            '商品编号',
            '供应商',
            '总库存',
            '总销量',
            '商品类别',
            '商品标签',
            '抢购时间',
            '更新时间',
        ];
    }

    public function map($row): array
    {
        $row = $row->toArray();

        return [
            $row['numbering'],
            $row['commodity']['name'],
            $row['commodity']['numbering'],
            $row['commodity']['supplier']['name'] ?? '',
            array_reduce($row['skus'], fn($total, $current) => $total + $current['stock'], 0),
            array_reduce($row['skus'], fn($total, $current) => $total + $current['sales'], 0),
            $row['commodity']['category']['name'] ?? '',
            implode(';', array_column($row['labels'], 'name')),
            $row['panic_buying_start_time'] . ' 至 ' . $row['panic_buying_end_time'],
            $row['updated_at']
        ];
    }

    /**
     * @return \Illuminate\Database\Query\Builder
     */
    public function query()
    {
        return CommodityActivity::query()
            ->with([
                'labels.attachments',
                'commodity' => function ($builder) {
                    $builder
                        ->withTrashed()
                        ->with(['category', 'supplier']);
                },
                'attachments' => function (MorphToMany $morphToMany) {
                    $morphToMany
                        ->wherePivot('type', CommodityActivity::ATTACHMENT_TYPE_MAIN_PIC);
                },
                'skus:commodity_activity_id,id,stock,sales'
            ])
            ->when($this->request['label'] ?? 0, function (Builder $builder, $label) {
                $builder->whereHas('labels', function (Builder $builder) use ($label) {
                    $builder->where('label_id', $label);
                });
            })
            ->when(($this->request['name'] ?? '') || ($this->request['category'] ?? 0) || ($this->request['numbering'] ?? ''),
                function (Builder $builder) {
                    $builder
                        ->join('commodities', 'commodities.id', '=', 'commodity_activities.commodity_id')
                        ->when($this->request['name'] ?? '', function (Builder $builder, $name) {
                            $builder->where('commodities.name', 'like', "%$name%");
                        })
                        ->when($this->request['category'] ?? 0, function (Builder $builder, $category) {
                            $builder->where('commodities.category_id', $category);
                        })
                        ->when($this->request['numbering'] ?? '', function (Builder $builder, $numbering) {
                            $builder->where('commodities.numbering', 'like', "%$numbering%");
                        });
                })
            ->when($this->request['activity_numbering'] ?? '', function (Builder $builder, $activityNumbering) {
                $builder->where('commodity_activities.numbering', 'like', "$activityNumbering%");
            })
            ->when($this->request['type'] ?? 0, function (Builder $builder, $type) {
                $builder->where('commodity_activities.type', $type);
            })
            ->when($this->request['locking'] ?? 0, function (Builder $builder, $locking) {
                $builder->where('commodity_activities.locking', $locking);
            })
            ->when($this->request['updated_at_begin'] ?? '', function (Builder $query, $createdAtBegin) {
                $query->where('commodity_activities.updated_at', '>=', $createdAtBegin);
            })
            ->when($this->request['updated_at_end'] ?? '', function (Builder $query, $createdAtEnd) {
                $query->where('commodity_activities.updated_at', '<=', Carbon::parse($createdAtEnd)->endOfDay());
            })
            ->when($this->request['panic_buying_start_time'] ?? '' && $this->request['panic_buying_end_time'] ?? '', function (Builder $builder) {
                $betweenArr = [
                    Carbon::parse($this->request['panic_buying_start_time'] ?? '')->startOfDay()->format('Y-m-d H:i:s'),
                    Carbon::parse($this->request['panic_buying_end_time'] ?? '')->endOfDay()->format('Y-m-d H:i:s')
                ];
                $builder->whereBetween('commodity_activities.panic_buying_start_time', $betweenArr);
            })
            ->when($this->request['status'] ?? 0, function (Builder $query, $status) {
                if ((int) $status === CommodityActivity::STATUS_OVER) {
                    $query->where('panic_buying_end_time', '<=', Carbon::now());
                } else {
                    $query->where('commodity_activities.status', $status);
                }
            })
            ->select(['commodity_activities.*']);
    }
}
